<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodsItem :goods="good" />
      </li>
    </ul>
    <!-- XtxInfiniteLoad 进入可视区 就会触发load发请求 -->
    <XtxInfiniteLoad
      :isLoading="isLoading"
      :isFinished="isFinished"
      @load="loadNextPage"
    />
  </div>
</template>

<script>
import GoodsItem from './goods-item.vue'
import { findSubCategoryGoods } from '@/api/category'
import { ref, watch, inject } from 'vue'
import { useRoute } from 'vue-router'
export default {
  components: {
    GoodsItem
  },
  setup () {
    // 商品列表
    const goodList = ref([])
    const route = useRoute()
    // 上拉加载更多
    const isLoading = ref(false)
    const isFinished = ref(false)
    // 请求需要的数据(不需要响应式，就定义为普通js对象)
    const reqParams = {
      page: 0,
      pageSize: 20,
      categoryId: route.params.id,
      // 筛选条件数据
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }
    // 接收过滤条件数据
    const filterParams = inject('filterParams')
    watch(() => filterParams.value, (newVal) => {
      console.log('筛选条件变化了：', newVal)
      /**
       * 1. 合并参数（合并最新的过滤条件）
       * 2. 拿到最新参数发请求
       */
      goodList.value = []
      reqParams.page = 0
      isFinished.value = false
      // const newReqParams = { ...reqParams, ...newVal }
      // getGoodList(newReqParams)
    }, { deep: true })

    // const getGoodList = async (params) => {
    //   const { result } = await findSubCategoryGoods(params)
    //   console.log('列表：', result)
    //   goodList.value = result.items
    // }

    // 加载下一页数据
    const loadNextPage = async () => {
      /**
         * 1. 把列表状态修改为加载中isLoading=true和页码加1
         * 2. 发请求
         * 3. 请求完毕，isLoading=false,代表列表加载完
         * 4. 判断列表数据是否加载完成=》如果加载完成，需要把isFinished改成true
         */
      isLoading.value = true
      reqParams.page++
      const { result } = await findSubCategoryGoods({ ...reqParams, ...filterParams.value })
      // 追加
      goodList.value.push(...result.items)
      isLoading.value = false
      if (goodList.value.length === result.counts) {
        // 加载完了
        isFinished.value = true
      }
    }
    // onMounted(() => {
    //   getGoodList(reqParams)
    // })

    return {
      goodList,
      isLoading,
      isFinished,
      loadNextPage
    }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
